<template>
  <div class="cont">
    <el-form ref="form"  :rules="rules" :model="formData" label-width="120px">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="简短介绍" prop="front_name">
        <el-input v-model="formData.front_name"></el-input>
      </el-form-item>
      <el-form-item label="分类图片" prop="img_url">
        <el-upload
          :action="uploadImgToQiNiuUrl"
          ref="cUpload"
          :on-success="cUploadSuccess"
          :on-change="cUploadChange"
          :limit="1"
          list-type="picture"
          :file-list='cFileList'
          :on-remove="cUploadRemove"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <template #tip>
             <div class="el-upload__tip">图片尺寸：顶级分类为690*自定义, 只能上传jpg/png文件</div>  
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="分类图片高度" prop="p_height">
        <el-input v-model="formData.p_height"></el-input>
      </el-form-item>
      <el-form-item label="图标" prop="icon_url">
        <el-upload
          :action="uploadImgToQiNiuUrl"
          ref="cIconUpload"
          :limit="1"
          list-type="picture"
          :on-success="iconUploadSuccess"
          :file-list='iconFileList'
          :on-remove="cIconRemove"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <template #tip>
             <div class="el-upload__tip">图片尺寸：图标250*250, 只能上传jpg/png文件</div>  
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="排序" prop="sort_order">
        <el-input-number
          v-model="formData.sort_order"
          @change="handleChange"
          :min="1"
          :max="10" 
          label="描述文字"
          ></el-input-number>
      </el-form-item>
      <el-form-item>
        <el-button @click="submit" type="primary">确定保存</el-button>
        <el-button @click="reset">取消</el-button>
      </el-form-item>
      
    </el-form>
  </div>
</template>
<script>
import { uploadImgToQiNiuUrl }  from '@/api/common.js'
import { addCategory,getCategoryById,updateCategory } from '@/api/product.js'
export default {
  name:'商品分类',
  data(){
    return {
      uploadImgToQiNiuUrl,
      formData: {
        name:'',
        front_name:'', // 简介
        img_url:'', // 分类图片
        p_height:'', // 分类图片高度
        icon_url:'', // 图标地址
        sort_order:'', // 排序
        parent_id:0,
      },
      rules:{
        name:[
          { required: true, message: '请输入分类名称', trigger: 'blur'}
        ],
        img_url:[
          { required: true, message: '分类图片不能为空', trigger: 'blur'}
        ],
        p_height:[
          { required: true, message: '分类图片高度不能为空', trigger: 'blur'}
        ],
        icon_url:[
          { required: true, message: '图标不能为空', trigger: 'blur'}
        ]
      },
      cFileList:[],
      iconFileList:[],
      type:'add'
      
    }
  },
  mounted(){
    this.init()
  },
  methods:{
    async init(){
      let id = this.$route.query.id
      if(id){
        this.type = 'edit'
        let res = await getCategoryById(id)
        if(res.code === 0){
          this.formData = res.data
          this.cFileList = [
            {url:res.data.img_url}
          ]
          this.iconFileList = [
            {
              url:res.data.icon_url
            }
          ]
        }else{
          this.$message({
            type:'error',
            message:'获取分类详情失败'
          })
        }
      }else{
        this.type = 'add'
      }
      
      
    },
    createImgUrl(file){
      if(file){
        let imgUrl = ''
        if(window.createObjectURL !== undefined){
          imgUrl = window.createObjectURL(file)
        }else if(window.URL !== undefined){
          imgUrl = window.URL.createObjectURL(file)
        }
        return imgUrl
      }
      
    },
    cUploadSuccess(response, file, fileList){
      if(response.code === 0){
          this.formData.img_url = response.data.url
      }
      this.cFileList=[
        {
          name:file.name,
          url:response.data.url
        }
      ]
      this.$refs.form.clearValidate('img_url')
      
      // console.log('cUploadSuccess:',response, file, fileList)
    },
    iconUploadSuccess(response,file,fileList){
      if(response.code === 0){
          this.formData.icon_url = response.data.url
      }
      console.log('iconUploadSuccess:',response, file, fileList)
      this.iconFileList = [
        {
          name:file.name,
          url:response.data.url
        }
      ]
      this.$refs.form.clearValidate('icon_url')
    },
    async submit(){      
      this.formData.level = this.formData.parent_id == 0 ? '1' : '2';
      this.$refs.form.validate(async(valid)=>{
        // 验证通过
        if(valid){
          // 新增
          if(this.type === 'add'){
            let res = await addCategory(this.formData)
            if(res.code === 0){
              this.$message({
                type:'success',
                message:'新增分类成功'
              })
              this.reset()
            }else{
              this.$message({
                type:'error',
                message:res.msg
              })
            }
          }else {
            // 编辑
            let res = await updateCategory(this.formData)
            if(res.code === 0){
              this.$message({
                type:'success',
                message:'修改分类成功'
              })
              this.reset()
            }else{
              this.$message({
                type:'error',
                message:res.msg
              })
            }
          }
          
        }
        
      })
    },

    reset(){
      this.$refs.form.resetFields()
      // 清空上传文件
      this.$refs.cUpload.clearFiles()
      this.$refs.cIconUpload.clearFiles()
    },
    cUploadRemove(file,fileList){
      this.formData.img_url = ''
    },
    cIconRemove(){
      this.formData.icon_url = ''
    }
  }
}
</script>
<style lang="scss" scoped>
.cont{
  .el-form{
    width: 500px;
    text-align: left;
  }
}
</style>

